selected = 0
received = 0
sent = 0
text = {}
color = {}
msg = ""

function receiveText(data, length, from)
   if msg ~= nil then
      msg = nil
   end
   msg = data
   received = received + 1
end

Nifi.setStreamHandler(0x0001, receiveText)

while not Keys.held.Start do
   
   Controls.read()
   
   users = Nifi.getNumberOfKnownUsers()
   
   if Keys.newPress.Down then
      selected = selected + 1
   end
   if Keys.newPress.Up then
      selected = selected - 1
   end
   if users > 0 then
      selected = selected % users
   end
   if Keys.newPress.L then
      Nifi.createRoom("Our room", 2, 1, 1)
   end
   if Keys.newPress.A then
      Nifi.sendToUser(Nifi.getUserByID(selected), 0x0001, {"Key [A] pressed."}, 17) ;
      sent = sent + 1
   end
   if Keys.newPress.B then
      Nifi.sendToUser(Nifi.getUserByID(selected), 0x0001, {"Key [B] pressed."}, 17) ;
      sent = sent + 1
   end
   if Keys.newPress.X then
      Nifi.sendToUser(Nifi.getUserByID(selected), 0x0001, {"Key [X] pressed."}, 17) ;
      sent = sent + 1
   end
   if Keys.newPress.Y then
      Nifi.sendToUser(Nifi.getUserByID(selected), 0x0001, {"Key [Y] pressed."}, 17) ;
      sent = sent + 1
   end
   if Keys.newPress.Select then
      Nifi.sendToUser(Nifi.getUserByID(selected), 0x8001, {"..."}, 17) ;
   end
   if Keys.newPress.R then
      Nifi.sendToUser(Nifi.getUserByID(selected), 0x0001, {"..."}, 17) ;
      sent = sent + 1
   end
   
   -- Display all users
   for i = 0, users-1 do
      local user = Nifi.getUserByID(i)
      
      local timeout = "OK"
      if Nifi.isTimedOut(user) then
         timeout = "TIMEOUT"
      end
      
      if i == selected then
         color[i] = Color.new(0, 31, 31)
      else
         color[i] = Color.new(31, 31, 31)
      end
      
      text[i] = Nifi.getUserName(user).." ("..timeout..")"
      
      screen.print(SCREEN_DOWN, 5, (i-1)*11+5, "User "..text[i].." has received your data : "..Nifi.userIsStreamSent(user, 0x0001), color[i])
   end
   
   screen.print(SCREEN_UP, 5, 15, "Received : "..received.." Sent : "..sent)
   screen.print(SCREEN_UP, 5, 25, "Last Received Text : "..msg)
   
   render()
   
   Nifi.update()
   
end
